package tcu.yuyp.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import tcu.yuyp.pojo.R;
import tcu.yuyp.pojo.User;
import tcu.yuyp.service.impl.MembersService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


//@ServletComponentScan
@WebServlet("/members")
public class MembersServlet extends HttpServlet {
    MembersService membersService;
    List<User> userList = new ArrayList<>();

    public MembersServlet(MembersService membersService) {
        this.membersService = membersService;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //查看参加旅游的所有人员的名单
        //设置响应的数据格式和编码信息
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        ObjectMapper mapper = new ObjectMapper();//创建jackson库提供的ObjectMapper类的实体对象
        R r = new R();

        //调用service层的查看参加旅游的所有人员的名单的方法
        membersService.getMembersResponse(userList,r);

        resp.getWriter().println(mapper.writeValueAsString(r));//将r转化为json型相应给浏览器客户端

//        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //报名参加旅游

        var mapper = new ObjectMapper();
        var r = new R();

        //设置响应的数据格式和字符编码
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        //获取请求体
        User newUser = mapper.readValue(req.getReader(), User.class);//将json类型的请求体数据解析为User类数据

        //调用service层的方法进行判断
        membersService.postMembersResponse(userList,newUser,r);
        resp.getWriter().println(mapper.writeValueAsString(r));//响应数据


//        super.doPost(req, resp);//避免出现405报错，导致GET和POST请求出现问题
    }
}
